/*
 * sample_current.c
 *
 *  Created on: Nov 25, 2024
 *      Author: Vinson
 */
#include "sample_current.h"
#include "adc.h"
#include "micros.h"
#include "utils.h"

extern ADC_HandleTypeDef hadc1;
extern ADC_HandleTypeDef hadc2;

static current_sense_t adc_sense;

/*
 * 获取注入通道转发结果
 */
static float adc_voltage_read(const ADC_HandleTypeDef *hadc)
{
	int32_t raw_adc = HAL_ADCEx_InjectedGetValue(hadc, ADC_INJECTED_RANK_1);
    return raw_adc * _ADC_CONV;
}

static void adc_calibrateOffsets()
{
	int calibration_rounds = 1000;

	// 查找0电流时候的电压
	adc_sense.offset_ch1 = 0;
	adc_sense.offset_ch2 = 0;
	// 读数1000次
	for (int i = 0; i < calibration_rounds; i++) {
		adc_sense.offset_ch1 += adc_voltage_read(&hadc1);
		adc_sense.offset_ch2 += adc_voltage_read(&hadc2);
		delay_us(1);
	}
	// 求平均, 得到误差
	adc_sense.offset_ch1 = adc_sense.offset_ch1 / calibration_rounds; // 1.46
	adc_sense.offset_ch2 = adc_sense.offset_ch2 / calibration_rounds; // 1.46
	printf("adc->offset_ch1: %.2f, adc->offset_ch2: %.2f\n", adc_sense.offset_ch1, adc_sense.offset_ch2);

}

static void get_3phaseCurrent(current_sense_t *adc)
{
	 float adc1_value = (adc_voltage_read(&hadc1) - adc->offset_ch1) * _ADC_GAIN;
	 float adc2_value = (adc_voltage_read(&hadc2) - adc->offset_ch2) * _ADC_GAIN;

	//if (print_cnt-- == 0) {
		  /* 用于上位机波形显示，打印开启会降低电机转速 */
		//printf("%f,%f \n", adc1_value, adc2_value);
		//print_cnt = PRINT_LOOP_NUMBER;
	//}


	 ADC_TYPE type = adc->adc_type;
	 switch(type) {
     case ADC_GET_AB:
          adc->ia = adc1_value;
          adc->ib = adc2_value;
          adc->ic = -(adc1_value + adc2_value);
          break;
     case ADC_GET_AC:
          adc->ia = adc1_value;
          adc->ib = -(adc1_value +  adc2_value);
          adc->ic = adc2_value;
          break;
     case ADC_GET_BA:
          adc->ia = adc2_value;
          adc->ib = adc1_value;
          adc->ic = -(adc1_value +  adc2_value);
          break;
     case ADC_GET_BC:
    	  adc->ia = -(adc1_value + adc2_value);
          adc->ib = adc1_value;
          adc->ic = adc2_value;
          break;
     case ADC_GET_CA:
    	  adc->ia = adc2_value;
          adc->ib = -(adc1_value + adc2_value);
          adc->ic = adc1_value;
          break;
     case ADC_GET_CB:
    	  adc->ia = -(adc1_value + adc2_value);
          adc->ib = adc2_value;
          adc->ic = adc1_value;
          break;
	 }
}

void adc_get_phaseCurrent(float *ia, float *ib)
{
	get_3phaseCurrent(&adc_sense);
	*ia = adc_sense.ia;
	*ib = adc_sense.ib;
}

void adc_current_init()
{
    /* Step1: ADC JSQR 配置 */
    printf("hadc1.Instance->JSQR: 0x%08lx\n", hadc1.Instance->JSQR);
    printf("hadc2.Instance->JSQR: 0x%08lx\n", hadc2.Instance->JSQR);
    adc_sense.adc_type = ADC_GET_AC;
    //adc_sense.adc_type = ADC_GET_AC;

    adc_calibrateOffsets();
}

void adc_current_dir_set(ADC_TYPE type)
{
	adc_sense.adc_type = type;
}
